<template>
  <div class='allocMenu'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>分配权限</span>
      </div>
      <el-tree
        ref="menu-tree"
        :data="menu"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="checkedkeys"
      >
      </el-tree>
      <div class="bottom">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="resetChecked">清空</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang='ts'>
import Vue from 'vue'
import { getMenuNodeList, allocateRoleMenus, getRolemenus } from '@/services/menu'
import { Tree } from 'element-ui'
export default Vue.extend({
  name: 'allocMenu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      menu: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedkeys: []
    }
  },
  created () {
    this.getMenuList()
    this.getRoleMenus()
  },
  methods: {
    async getRoleMenus () {
      const { data } = await getRolemenus(this.roleId)
      if (data.code === '000000') {
        this.getCheckedKey(data.data)
      }
    },
    getCheckedKey (menu: any) {
      menu.forEach((element: any) => {
        if (element.selected) {
          this.checkedkeys = [...this.checkedkeys, element.id] as any
        }
        if (element.subMenuList) {
          this.getCheckedKey(element.subMenuList)
        }
      })
    },
    async getMenuList () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menu = data.data
      }
    },
    async onSubmit () {
      const menuIdList = (this.$refs['menu-tree'] as Tree).getCheckedKeys()
      const { data } = await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList
      })
      this.$router.back()
    },
    resetChecked () {
      (this.$refs['menu-tree'] as Tree).setCheckedKeys([])
    }
  }
})
</script>
<style lang='scss' scoped>
.bottom {
  margin-top:20px ;
  display: flex;
  justify-content: center;
}
</style>
